const knex = require('../../lib/db')

function baseCRUD(tableName) {
  // 查询分页
  async function findPage(current, size, rule = {}, extend) {
    const queryExec = extend ? extend(knex(tableName)) : knex(tableName).where(rule)
    const totalExec = extend ? extend(knex(tableName)) : knex(tableName).where(rule)
    const offset = (current - 1) * size
    const total = await totalExec.count('id as total')
    const records = await queryExec.offset(offset).limit(size)

    return {
      current,
      size,
      total: Number(total?.[0]?.total ?? 0),
      records
    }
  }

  // 查询所有
  function findAll(rule = {}, current, size = 10) {
    if (current !== undefined && size !== undefined) {
      return findPage(current, size, rule)
    }
    if (Object.keys(rule).length) {
      return knex(tableName).where(rule)
    }
    return knex(tableName)
  }

  // 创建
  function create(data, operator = 'admin') {
    return findAll()
      .insert({ ...data, created_by: operator, created_at: new Date() })
      .returning('*')
  }

  // 查询单个
  function findOne(rule) {
    if (['string', 'number'].includes(typeof rule)) {
      return findAll().where('id', rule).first()
    }
    return findAll(rule).first()
  }

  // 更新
  function update(id, data, operator = 'admin') {
    return findAll()
      .where('id', id)
      .update({ ...data, updated_at: new Date(), updated_by: operator })
      .returning('*')
  }

  // 删除
  function remove(ids) {
    let idsArr = Array.isArray(ids) ? ids : ids.split(',')
    return findAll().whereIn('id', idsArr).del()
  }

  return {
    findAll,
    findPage,
    create,
    findOne,
    update,
    remove
  }
}

module.exports = baseCRUD
